home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / codecs.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  35KB  |  1,059 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import __builtin__
  13. import sys
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError('Failed to load the builtin codecs: %s' % why)
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE',
  33.     'BOM_UTF8',
  34.     'BOM_UTF16',
  35.     'BOM_UTF16_LE',
  36.     'BOM_UTF16_BE',
  37.     'BOM_UTF32',
  38.     'BOM_UTF32_LE',
  39.     'BOM_UTF32_BE',
  40.     'strict_errors',
  41.     'ignore_errors',
  42.     'replace_errors',
  43.     'xmlcharrefreplace_errors',
  44.     'register_error',
  45.     'lookup_error']
  46. BOM_UTF8 = '\xef\xbb\xbf'
  47. BOM_LE = BOM_UTF16_LE = '\xff\xfe'
  48. BOM_BE = BOM_UTF16_BE = '\xfe\xff'
  49. BOM_UTF32_LE = '\xff\xfe\x00\x00'
  50. BOM_UTF32_BE = '\x00\x00\xfe\xff'
  51. if sys.byteorder == 'little':
  52.     BOM = BOM_UTF16 = BOM_UTF16_LE
  53.     BOM_UTF32 = BOM_UTF32_LE
  54. else:
  55.     BOM = BOM_UTF16 = BOM_UTF16_BE
  56.     BOM_UTF32 = BOM_UTF32_BE
  57. BOM32_LE = BOM_UTF16_LE
  58. BOM32_BE = BOM_UTF16_BE
  59. BOM64_LE = BOM_UTF32_LE
  60. BOM64_BE = BOM_UTF32_BE
  61.  
  62. class CodecInfo(tuple):
  63.     
  64.     def __new__(cls, encode, decode, streamreader = None, streamwriter = None, incrementalencoder = None, incrementaldecoder = None, name = None):
  65.         self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  66.         self.name = name
  67.         self.encode = encode
  68.         self.decode = decode
  69.         self.incrementalencoder = incrementalencoder
  70.         self.incrementaldecoder = incrementaldecoder
  71.         self.streamwriter = streamwriter
  72.         self.streamreader = streamreader
  73.         return self
  74.  
  75.     
  76.     def __repr__(self):
  77.         return '<%s.%s object for encoding %s at 0x%x>' % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
  78.  
  79.  
  80.  
  81. class Codec:
  82.     """ Defines the interface for stateless encoders/decoders.
  83.  
  84.         The .encode()/.decode() methods may use different error
  85.         handling schemes by providing the errors argument. These
  86.         string values are predefined:
  87.  
  88.          'strict' - raise a ValueError error (or a subclass)
  89.          'ignore' - ignore the character and continue with the next
  90.          'replace' - replace with a suitable replacement character;
  91.                     Python will use the official U+FFFD REPLACEMENT
  92.                     CHARACTER for the builtin Unicode codecs on
  93.                     decoding and '?' on encoding.
  94.          'xmlcharrefreplace' - Replace with the appropriate XML
  95.                                character reference (only for encoding).
  96.          'backslashreplace'  - Replace with backslashed escape sequences
  97.                                (only for encoding).
  98.  
  99.         The set of allowed values can be extended via register_error.
  100.  
  101.     """
  102.     
  103.     def encode(self, input, errors = 'strict'):
  104.         """ Encodes the object input and returns a tuple (output
  105.             object, length consumed).
  106.  
  107.             errors defines the error handling to apply. It defaults to
  108.             'strict' handling.
  109.  
  110.             The method may not store state in the Codec instance. Use
  111.             StreamCodec for codecs which have to keep state in order to
  112.             make encoding/decoding efficient.
  113.  
  114.             The encoder must be able to handle zero length input and
  115.             return an empty object of the output object type in this
  116.             situation.
  117.  
  118.         """
  119.         raise NotImplementedError
  120.  
  121.     
  122.     def decode(self, input, errors = 'strict'):
  123.         """ Decodes the object input and returns a tuple (output
  124.             object, length consumed).
  125.  
  126.             input must be an object which provides the bf_getreadbuf
  127.             buffer slot. Python strings, buffer objects and memory
  128.             mapped files are examples of objects providing this slot.
  129.  
  130.             errors defines the error handling to apply. It defaults to
  131.             'strict' handling.
  132.  
  133.             The method may not store state in the Codec instance. Use
  134.             StreamCodec for codecs which have to keep state in order to
  135.             make encoding/decoding efficient.
  136.  
  137.             The decoder must be able to handle zero length input and
  138.             return an empty object of the output object type in this
  139.             situation.
  140.  
  141.         """
  142.         raise NotImplementedError
  143.  
  144.  
  145.  
  146. class IncrementalEncoder(object):
  147.     '''
  148.     An IncrementalEncoder encodes an input in multiple steps. The input can be
  149.     passed piece by piece to the encode() method. The IncrementalEncoder remembers
  150.     the state of the Encoding process between calls to encode().
  151.     '''
  152.     
  153.     def __init__(self, errors = 'strict'):
  154.         '''
  155.         Creates an IncrementalEncoder instance.
  156.  
  157.         The IncrementalEncoder may use different error handling schemes by
  158.         providing the errors keyword argument. See the module docstring
  159.         for a list of possible values.
  160.         '''
  161.         self.errors = errors
  162.         self.buffer = ''
  163.  
  164.     
  165.     def encode(self, input, final = False):
  166.         '''
  167.         Encodes input and returns the resulting object.
  168.         '''
  169.         raise NotImplementedError
  170.  
  171.     
  172.     def reset(self):
  173.         '''
  174.         Resets the encoder to the initial state.
  175.         '''
  176.         pass
  177.  
  178.     
  179.     def getstate(self):
  180.         '''
  181.         Return the current state of the encoder.
  182.         '''
  183.         return 0
  184.  
  185.     
  186.     def setstate(self, state):
  187.         '''
  188.         Set the current state of the encoder. state must have been
  189.         returned by getstate().
  190.         '''
  191.         pass
  192.  
  193.  
  194.  
  195. class BufferedIncrementalEncoder(IncrementalEncoder):
  196.     '''
  197.     This subclass of IncrementalEncoder can be used as the baseclass for an
  198.     incremental encoder if the encoder must keep some of the output in a
  199.     buffer between calls to encode().
  200.     '''
  201.     
  202.     def __init__(self, errors = 'strict'):
  203.         IncrementalEncoder.__init__(self, errors)
  204.         self.buffer = ''
  205.  
  206.     
  207.     def _buffer_encode(self, input, errors, final):
  208.         raise NotImplementedError
  209.  
  210.     
  211.     def encode(self, input, final = False):
  212.         data = self.buffer + input
  213.         (result, consumed) = self._buffer_encode(data, self.errors, final)
  214.         self.buffer = data[consumed:]
  215.         return result
  216.  
  217.     
  218.     def reset(self):
  219.         IncrementalEncoder.reset(self)
  220.         self.buffer = ''
  221.  
  222.     
  223.     def getstate(self):
  224.         if not self.buffer:
  225.             pass
  226.         return 0
  227.  
  228.     
  229.     def setstate(self, state):
  230.         if not state:
  231.             pass
  232.         self.buffer = ''
  233.  
  234.  
  235.  
  236. class IncrementalDecoder(object):
  237.     '''
  238.     An IncrementalDecoder decodes an input in multiple steps. The input can be
  239.     passed piece by piece to the decode() method. The IncrementalDecoder
  240.     remembers the state of the decoding process between calls to decode().
  241.     '''
  242.     
  243.     def __init__(self, errors = 'strict'):
  244.         '''
  245.         Creates a IncrementalDecoder instance.
  246.  
  247.         The IncrementalDecoder may use different error handling schemes by
  248.         providing the errors keyword argument. See the module docstring
  249.         for a list of possible values.
  250.         '''
  251.         self.errors = errors
  252.  
  253.     
  254.     def decode(self, input, final = False):
  255.         '''
  256.         Decodes input and returns the resulting object.
  257.         '''
  258.         raise NotImplementedError
  259.  
  260.     
  261.     def reset(self):
  262.         '''
  263.         Resets the decoder to the initial state.
  264.         '''
  265.         pass
  266.  
  267.     
  268.     def getstate(self):
  269.         '''
  270.         Return the current state of the decoder.
  271.  
  272.         This must be a (buffered_input, additional_state_info) tuple.
  273.         buffered_input must be a bytes object containing bytes that
  274.         were passed to decode() that have not yet been converted.
  275.         additional_state_info must be a non-negative integer
  276.         representing the state of the decoder WITHOUT yet having
  277.         processed the contents of buffered_input.  In the initial state
  278.         and after reset(), getstate() must return (b"", 0).
  279.         '''
  280.         return ('', 0)
  281.  
  282.     
  283.     def setstate(self, state):
  284.         '''
  285.         Set the current state of the decoder.
  286.  
  287.         state must have been returned by getstate().  The effect of
  288.         setstate((b"", 0)) must be equivalent to reset().
  289.         '''
  290.         pass
  291.  
  292.  
  293.  
  294. class BufferedIncrementalDecoder(IncrementalDecoder):
  295.     '''
  296.     This subclass of IncrementalDecoder can be used as the baseclass for an
  297.     incremental decoder if the decoder must be able to handle incomplete byte
  298.     sequences.
  299.     '''
  300.     
  301.     def __init__(self, errors = 'strict'):
  302.         IncrementalDecoder.__init__(self, errors)
  303.         self.buffer = ''
  304.  
  305.     
  306.     def _buffer_decode(self, input, errors, final):
  307.         raise NotImplementedError
  308.  
  309.     
  310.     def decode(self, input, final = False):
  311.         data = self.buffer + input
  312.         (result, consumed) = self._buffer_decode(data, self.errors, final)
  313.         self.buffer = data[consumed:]
  314.         return result
  315.  
  316.     
  317.     def reset(self):
  318.         IncrementalDecoder.reset(self)
  319.         self.buffer = ''
  320.  
  321.     
  322.     def getstate(self):
  323.         return (self.buffer, 0)
  324.  
  325.     
  326.     def setstate(self, state):
  327.         self.buffer = state[0]
  328.  
  329.  
  330.  
  331. class StreamWriter(Codec):
  332.     
  333.     def __init__(self, stream, errors = 'strict'):
  334.         """ Creates a StreamWriter instance.
  335.  
  336.             stream must be a file-like object open for writing
  337.             (binary) data.
  338.  
  339.             The StreamWriter may use different error handling
  340.             schemes by providing the errors keyword argument. These
  341.             parameters are predefined:
  342.  
  343.              'strict' - raise a ValueError (or a subclass)
  344.              'ignore' - ignore the character and continue with the next
  345.              'replace'- replace with a suitable replacement character
  346.              'xmlcharrefreplace' - Replace with the appropriate XML
  347.                                    character reference.
  348.              'backslashreplace'  - Replace with backslashed escape
  349.                                    sequences (only for encoding).
  350.  
  351.             The set of allowed parameter values can be extended via
  352.             register_error.
  353.         """
  354.         self.stream = stream
  355.         self.errors = errors
  356.  
  357.     
  358.     def write(self, object):
  359.         """ Writes the object's contents encoded to self.stream.
  360.         """
  361.         (data, consumed) = self.encode(object, self.errors)
  362.         self.stream.write(data)
  363.  
  364.     
  365.     def writelines(self, list):
  366.         ''' Writes the concatenated list of strings to the stream
  367.             using .write().
  368.         '''
  369.         self.write(''.join(list))
  370.  
  371.     
  372.     def reset(self):
  373.         ''' Flushes and resets the codec buffers used for keeping state.
  374.  
  375.             Calling this method should ensure that the data on the
  376.             output is put into a clean state, that allows appending
  377.             of new fresh data without having to rescan the whole
  378.             stream to recover state.
  379.  
  380.         '''
  381.         pass
  382.  
  383.     
  384.     def seek(self, offset, whence = 0):
  385.         self.stream.seek(offset, whence)
  386.         if whence == 0 and offset == 0:
  387.             self.reset()
  388.  
  389.     
  390.     def __getattr__(self, name, getattr = getattr):
  391.         ''' Inherit all other methods from the underlying stream.
  392.         '''
  393.         return getattr(self.stream, name)
  394.  
  395.     
  396.     def __enter__(self):
  397.         return self
  398.  
  399.     
  400.     def __exit__(self, type, value, tb):
  401.         self.stream.close()
  402.  
  403.  
  404.  
  405. class StreamReader(Codec):
  406.     
  407.     def __init__(self, stream, errors = 'strict'):
  408.         """ Creates a StreamReader instance.
  409.  
  410.             stream must be a file-like object open for reading
  411.             (binary) data.
  412.  
  413.             The StreamReader may use different error handling
  414.             schemes by providing the errors keyword argument. These
  415.             parameters are predefined:
  416.  
  417.              'strict' - raise a ValueError (or a subclass)
  418.              'ignore' - ignore the character and continue with the next
  419.              'replace'- replace with a suitable replacement character;
  420.  
  421.             The set of allowed parameter values can be extended via
  422.             register_error.
  423.         """
  424.         self.stream = stream
  425.         self.errors = errors
  426.         self.bytebuffer = ''
  427.         self.charbuffer = ''
  428.         self.linebuffer = None
  429.  
  430.     
  431.     def decode(self, input, errors = 'strict'):
  432.         raise NotImplementedError
  433.  
  434.     
  435.     def read(self, size = -1, chars = -1, firstline = False):
  436.         ''' Decodes data from the stream self.stream and returns the
  437.             resulting object.
  438.  
  439.             chars indicates the number of characters to read from the
  440.             stream. read() will never return more than chars
  441.             characters, but it might return less, if there are not enough
  442.             characters available.
  443.  
  444.             size indicates the approximate maximum number of bytes to
  445.             read from the stream for decoding purposes. The decoder
  446.             can modify this setting as appropriate. The default value
  447.             -1 indicates to read and decode as much as possible.  size
  448.             is intended to prevent having to decode huge files in one
  449.             step.
  450.  
  451.             If firstline is true, and a UnicodeDecodeError happens
  452.             after the first line terminator in the input only the first line
  453.             will be returned, the rest of the input will be kept until the
  454.             next call to read().
  455.  
  456.             The method should use a greedy read strategy meaning that
  457.             it should read as much data as is allowed within the
  458.             definition of the encoding and the given size, e.g.  if
  459.             optional encoding endings or state markers are available
  460.             on the stream, these should be read too.
  461.         '''
  462.         if self.linebuffer:
  463.             self.charbuffer = ''.join(self.linebuffer)
  464.             self.linebuffer = None
  465.         while True:
  466.             if chars < 0:
  467.                 if size < 0 or self.charbuffer:
  468.                     break
  469.                 
  470.             elif len(self.charbuffer) >= size:
  471.                 break
  472.             
  473.         if len(self.charbuffer) >= chars:
  474.             break
  475.         if size < 0:
  476.             newdata = self.stream.read()
  477.         else:
  478.             newdata = self.stream.read(size)
  479.         data = self.bytebuffer + newdata
  480.         
  481.         try:
  482.             (newchars, decodedbytes) = self.decode(data, self.errors)
  483.         except UnicodeDecodeError:
  484.             exc = None
  485.             if firstline:
  486.                 (newchars, decodedbytes) = self.decode(data[:exc.start], self.errors)
  487.                 lines = newchars.splitlines(True)
  488.                 if len(lines) <= 1:
  489.                     raise 
  490.             else:
  491.                 raise 
  492.  
  493.         self.bytebuffer = data[decodedbytes:]
  494.         self.charbuffer += newchars
  495.         if not newdata:
  496.             break
  497.             continue
  498.         return result
  499.  
  500.     
  501.     def readline(self, size = None, keepends = True):
  502.         ''' Read one line from the input stream and return the
  503.             decoded data.
  504.  
  505.             size, if given, is passed as size argument to the
  506.             read() method.
  507.  
  508.         '''
  509.         readsize = None if self.linebuffer else 72
  510.         line = ''
  511.         while True:
  512.             data = self.read(readsize, firstline = True)
  513.             if data and data.endswith('\r'):
  514.                 data += self.read(size = 1, chars = 1)
  515.             
  516.         line += data
  517.         lines = line.splitlines(True)
  518.         if lines:
  519.             if len(lines) > 1:
  520.                 line = lines[0]
  521.                 del lines[0]
  522.                 if len(lines) > 1:
  523.                     lines[-1] += self.charbuffer
  524.                     self.linebuffer = lines
  525.                     self.charbuffer = None
  526.                 else:
  527.                     self.charbuffer = lines[0] + self.charbuffer
  528.                 if not keepends:
  529.                     line = line.splitlines(False)[0]
  530.                 break
  531.             line0withend = lines[0]
  532.             line0withoutend = lines[0].splitlines(False)[0]
  533.             if line0withend != line0withoutend:
  534.                 self.charbuffer = ''.join(lines[1:]) + self.charbuffer
  535.                 if keepends:
  536.                     line = line0withend
  537.                 else:
  538.                     line = line0withoutend
  539.                 break
  540.             
  541.         if not data or size is not None:
  542.             if line and not keepends:
  543.                 line = line.splitlines(False)[0]
  544.             break
  545.         if readsize < 8000:
  546.             readsize *= 2
  547.             continue
  548.         return line
  549.  
  550.     
  551.     def readlines(self, sizehint = None, keepends = True):
  552.         """ Read all lines available on the input stream
  553.             and return them as list of lines.
  554.  
  555.             Line breaks are implemented using the codec's decoder
  556.             method and are included in the list entries.
  557.  
  558.             sizehint, if given, is ignored since there is no efficient
  559.             way to finding the true end-of-line.
  560.  
  561.         """
  562.         data = self.read()
  563.         return data.splitlines(keepends)
  564.  
  565.     
  566.     def reset(self):
  567.         ''' Resets the codec buffers used for keeping state.
  568.  
  569.             Note that no stream repositioning should take place.
  570.             This method is primarily intended to be able to recover
  571.             from decoding errors.
  572.  
  573.         '''
  574.         self.bytebuffer = ''
  575.         self.charbuffer = u''
  576.         self.linebuffer = None
  577.  
  578.     
  579.     def seek(self, offset, whence = 0):
  580.         """ Set the input stream's current position.
  581.  
  582.             Resets the codec buffers used for keeping state.
  583.         """
  584.         self.stream.seek(offset, whence)
  585.         self.reset()
  586.  
  587.     
  588.     def next(self):
  589.         ''' Return the next decoded line from the input stream.'''
  590.         line = self.readline()
  591.         if line:
  592.             return line
  593.         raise None
  594.  
  595.     
  596.     def __iter__(self):
  597.         return self
  598.  
  599.     
  600.     def __getattr__(self, name, getattr = getattr):
  601.         ''' Inherit all other methods from the underlying stream.
  602.         '''
  603.         return getattr(self.stream, name)
  604.  
  605.     
  606.     def __enter__(self):
  607.         return self
  608.  
  609.     
  610.     def __exit__(self, type, value, tb):
  611.         self.stream.close()
  612.  
  613.  
  614.  
  615. class StreamReaderWriter:
  616.     ''' StreamReaderWriter instances allow wrapping streams which
  617.         work in both read and write modes.
  618.  
  619.         The design is such that one can use the factory functions
  620.         returned by the codec.lookup() function to construct the
  621.         instance.
  622.  
  623.     '''
  624.     encoding = 'unknown'
  625.     
  626.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  627.         ''' Creates a StreamReaderWriter instance.
  628.  
  629.             stream must be a Stream-like object.
  630.  
  631.             Reader, Writer must be factory functions or classes
  632.             providing the StreamReader, StreamWriter interface resp.
  633.  
  634.             Error handling is done in the same way as defined for the
  635.             StreamWriter/Readers.
  636.  
  637.         '''
  638.         self.stream = stream
  639.         self.reader = Reader(stream, errors)
  640.         self.writer = Writer(stream, errors)
  641.         self.errors = errors
  642.  
  643.     
  644.     def read(self, size = -1):
  645.         return self.reader.read(size)
  646.  
  647.     
  648.     def readline(self, size = None):
  649.         return self.reader.readline(size)
  650.  
  651.     
  652.     def readlines(self, sizehint = None):
  653.         return self.reader.readlines(sizehint)
  654.  
  655.     
  656.     def next(self):
  657.         ''' Return the next decoded line from the input stream.'''
  658.         return self.reader.next()
  659.  
  660.     
  661.     def __iter__(self):
  662.         return self
  663.  
  664.     
  665.     def write(self, data):
  666.         return self.writer.write(data)
  667.  
  668.     
  669.     def writelines(self, list):
  670.         return self.writer.writelines(list)
  671.  
  672.     
  673.     def reset(self):
  674.         self.reader.reset()
  675.         self.writer.reset()
  676.  
  677.     
  678.     def seek(self, offset, whence = 0):
  679.         self.stream.seek(offset, whence)
  680.         self.reader.reset()
  681.         if whence == 0 and offset == 0:
  682.             self.writer.reset()
  683.  
  684.     
  685.     def __getattr__(self, name, getattr = getattr):
  686.         ''' Inherit all other methods from the underlying stream.
  687.         '''
  688.         return getattr(self.stream, name)
  689.  
  690.     
  691.     def __enter__(self):
  692.         return self
  693.  
  694.     
  695.     def __exit__(self, type, value, tb):
  696.         self.stream.close()
  697.  
  698.  
  699.  
  700. class StreamRecoder:
  701.     ''' StreamRecoder instances provide a frontend - backend
  702.         view of encoding data.
  703.  
  704.         They use the complete set of APIs returned by the
  705.         codecs.lookup() function to implement their task.
  706.  
  707.         Data written to the stream is first decoded into an
  708.         intermediate format (which is dependent on the given codec
  709.         combination) and then written to the stream using an instance
  710.         of the provided Writer class.
  711.  
  712.         In the other direction, data is read from the stream using a
  713.         Reader instance and then return encoded data to the caller.
  714.  
  715.     '''
  716.     data_encoding = 'unknown'
  717.     file_encoding = 'unknown'
  718.     
  719.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  720.         ''' Creates a StreamRecoder instance which implements a two-way
  721.             conversion: encode and decode work on the frontend (the
  722.             input to .read() and output of .write()) while
  723.             Reader and Writer work on the backend (reading and
  724.             writing to the stream).
  725.  
  726.             You can use these objects to do transparent direct
  727.             recodings from e.g. latin-1 to utf-8 and back.
  728.  
  729.             stream must be a file-like object.
  730.  
  731.             encode, decode must adhere to the Codec interface, Reader,
  732.             Writer must be factory functions or classes providing the
  733.             StreamReader, StreamWriter interface resp.
  734.  
  735.             encode and decode are needed for the frontend translation,
  736.             Reader and Writer for the backend translation. Unicode is
  737.             used as intermediate encoding.
  738.  
  739.             Error handling is done in the same way as defined for the
  740.             StreamWriter/Readers.
  741.  
  742.         '''
  743.         self.stream = stream
  744.         self.encode = encode
  745.         self.decode = decode
  746.         self.reader = Reader(stream, errors)
  747.         self.writer = Writer(stream, errors)
  748.         self.errors = errors
  749.  
  750.     
  751.     def read(self, size = -1):
  752.         data = self.reader.read(size)
  753.         (data, bytesencoded) = self.encode(data, self.errors)
  754.         return data
  755.  
  756.     
  757.     def readline(self, size = None):
  758.         if size is None:
  759.             data = self.reader.readline()
  760.         else:
  761.             data = self.reader.readline(size)
  762.         (data, bytesencoded) = self.encode(data, self.errors)
  763.         return data
  764.  
  765.     
  766.     def readlines(self, sizehint = None):
  767.         data = self.reader.read()
  768.         (data, bytesencoded) = self.encode(data, self.errors)
  769.         return data.splitlines(1)
  770.  
  771.     
  772.     def next(self):
  773.         ''' Return the next decoded line from the input stream.'''
  774.         data = self.reader.next()
  775.         (data, bytesencoded) = self.encode(data, self.errors)
  776.         return data
  777.  
  778.     
  779.     def __iter__(self):
  780.         return self
  781.  
  782.     
  783.     def write(self, data):
  784.         (data, bytesdecoded) = self.decode(data, self.errors)
  785.         return self.writer.write(data)
  786.  
  787.     
  788.     def writelines(self, list):
  789.         data = ''.join(list)
  790.         (data, bytesdecoded) = self.decode(data, self.errors)
  791.         return self.writer.write(data)
  792.  
  793.     
  794.     def reset(self):
  795.         self.reader.reset()
  796.         self.writer.reset()
  797.  
  798.     
  799.     def __getattr__(self, name, getattr = getattr):
  800.         ''' Inherit all other methods from the underlying stream.
  801.         '''
  802.         return getattr(self.stream, name)
  803.  
  804.     
  805.     def __enter__(self):
  806.         return self
  807.  
  808.     
  809.     def __exit__(self, type, value, tb):
  810.         self.stream.close()
  811.  
  812.  
  813.  
  814. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  815.     """ Open an encoded file using the given mode and return
  816.         a wrapped version providing transparent encoding/decoding.
  817.  
  818.         Note: The wrapped version will only accept the object format
  819.         defined by the codecs, i.e. Unicode objects for most builtin
  820.         codecs. Output is also codec dependent and will usually be
  821.         Unicode as well.
  822.  
  823.         Files are always opened in binary mode, even if no binary mode
  824.         was specified. This is done to avoid data loss due to encodings
  825.         using 8-bit values. The default file mode is 'rb' meaning to
  826.         open the file in binary read mode.
  827.  
  828.         encoding specifies the encoding which is to be used for the
  829.         file.
  830.  
  831.         errors may be given to define the error handling. It defaults
  832.         to 'strict' which causes ValueErrors to be raised in case an
  833.         encoding error occurs.
  834.  
  835.         buffering has the same meaning as for the builtin open() API.
  836.         It defaults to line buffered.
  837.  
  838.         The returned wrapped file object provides an extra attribute
  839.         .encoding which allows querying the used encoding. This
  840.         attribute is only available if an encoding was specified as
  841.         parameter.
  842.  
  843.     """
  844.     if encoding is not None:
  845.         if 'U' in mode:
  846.             mode = mode.strip().replace('U', '')
  847.             if mode[:1] not in set('rwa'):
  848.                 mode = 'r' + mode
  849.             
  850.         if 'b' not in mode:
  851.             mode = mode + 'b'
  852.         
  853.     file = __builtin__.open(filename, mode, buffering)
  854.     if encoding is None:
  855.         return file
  856.     info = None(encoding)
  857.     srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  858.     srw.encoding = encoding
  859.     return srw
  860.  
  861.  
  862. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  863.     """ Return a wrapped version of file which provides transparent
  864.         encoding translation.
  865.  
  866.         Strings written to the wrapped file are interpreted according
  867.         to the given data_encoding and then written to the original
  868.         file as string using file_encoding. The intermediate encoding
  869.         will usually be Unicode but depends on the specified codecs.
  870.  
  871.         Strings are read from the file using file_encoding and then
  872.         passed back to the caller as string using data_encoding.
  873.  
  874.         If file_encoding is not given, it defaults to data_encoding.
  875.  
  876.         errors may be given to define the error handling. It defaults
  877.         to 'strict' which causes ValueErrors to be raised in case an
  878.         encoding error occurs.
  879.  
  880.         The returned wrapped file object provides two extra attributes
  881.         .data_encoding and .file_encoding which reflect the given
  882.         parameters of the same name. The attributes can be used for
  883.         introspection by Python programs.
  884.  
  885.     """
  886.     if file_encoding is None:
  887.         file_encoding = data_encoding
  888.     data_info = lookup(data_encoding)
  889.     file_info = lookup(file_encoding)
  890.     sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)
  891.     sr.data_encoding = data_encoding
  892.     sr.file_encoding = file_encoding
  893.     return sr
  894.  
  895.  
  896. def getencoder(encoding):
  897.     ''' Lookup up the codec for the given encoding and return
  898.         its encoder function.
  899.  
  900.         Raises a LookupError in case the encoding cannot be found.
  901.  
  902.     '''
  903.     return lookup(encoding).encode
  904.  
  905.  
  906. def getdecoder(encoding):
  907.     ''' Lookup up the codec for the given encoding and return
  908.         its decoder function.
  909.  
  910.         Raises a LookupError in case the encoding cannot be found.
  911.  
  912.     '''
  913.     return lookup(encoding).decode
  914.  
  915.  
  916. def getincrementalencoder(encoding):
  917.     """ Lookup up the codec for the given encoding and return
  918.         its IncrementalEncoder class or factory function.
  919.  
  920.         Raises a LookupError in case the encoding cannot be found
  921.         or the codecs doesn't provide an incremental encoder.
  922.  
  923.     """
  924.     encoder = lookup(encoding).incrementalencoder
  925.     if encoder is None:
  926.         raise LookupError(encoding)
  927.     return encoder
  928.  
  929.  
  930. def getincrementaldecoder(encoding):
  931.     """ Lookup up the codec for the given encoding and return
  932.         its IncrementalDecoder class or factory function.
  933.  
  934.         Raises a LookupError in case the encoding cannot be found
  935.         or the codecs doesn't provide an incremental decoder.
  936.  
  937.     """
  938.     decoder = lookup(encoding).incrementaldecoder
  939.     if decoder is None:
  940.         raise LookupError(encoding)
  941.     return decoder
  942.  
  943.  
  944. def getreader(encoding):
  945.     ''' Lookup up the codec for the given encoding and return
  946.         its StreamReader class or factory function.
  947.  
  948.         Raises a LookupError in case the encoding cannot be found.
  949.  
  950.     '''
  951.     return lookup(encoding).streamreader
  952.  
  953.  
  954. def getwriter(encoding):
  955.     ''' Lookup up the codec for the given encoding and return
  956.         its StreamWriter class or factory function.
  957.  
  958.         Raises a LookupError in case the encoding cannot be found.
  959.  
  960.     '''
  961.     return lookup(encoding).streamwriter
  962.  
  963.  
  964. def iterencode(iterator, encoding, errors = 'strict', **kwargs):
  965.     '''
  966.     Encoding iterator.
  967.  
  968.     Encodes the input strings from the iterator using a IncrementalEncoder.
  969.  
  970.     errors and kwargs are passed through to the IncrementalEncoder
  971.     constructor.
  972.     '''
  973.     encoder = getincrementalencoder(encoding)(errors, **kwargs)
  974.     for input in iterator:
  975.         output = encoder.encode(input)
  976.         if output:
  977.             yield output
  978.             continue
  979.     output = encoder.encode('', True)
  980.     if output:
  981.         yield output
  982.  
  983.  
  984. def iterdecode(iterator, encoding, errors = 'strict', **kwargs):
  985.     '''
  986.     Decoding iterator.
  987.  
  988.     Decodes the input strings from the iterator using a IncrementalDecoder.
  989.  
  990.     errors and kwargs are passed through to the IncrementalDecoder
  991.     constructor.
  992.     '''
  993.     decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  994.     for input in iterator:
  995.         output = decoder.decode(input)
  996.         if output:
  997.             yield output
  998.             continue
  999.     output = decoder.decode('', True)
  1000.     if output:
  1001.         yield output
  1002.  
  1003.  
  1004. def make_identity_dict(rng):
  1005.     ''' make_identity_dict(rng) -> dict
  1006.  
  1007.         Return a dictionary where elements of the rng sequence are
  1008.         mapped to themselves.
  1009.  
  1010.     '''
  1011.     res = { }
  1012.     for i in rng:
  1013.         res[i] = i
  1014.     
  1015.     return res
  1016.  
  1017.  
  1018. def make_encoding_map(decoding_map):
  1019.     ''' Creates an encoding map from a decoding map.
  1020.  
  1021.         If a target mapping in the decoding map occurs multiple
  1022.         times, then that target is mapped to None (undefined mapping),
  1023.         causing an exception when encountered by the charmap codec
  1024.         during translation.
  1025.  
  1026.         One example where this happens is cp875.py which decodes
  1027.         multiple character to \\u001a.
  1028.  
  1029.     '''
  1030.     m = { }
  1031.     for k, v in decoding_map.items():
  1032.         if v not in m:
  1033.             m[v] = k
  1034.             continue
  1035.         m[v] = None
  1036.     
  1037.     return m
  1038.  
  1039.  
  1040. try:
  1041.     strict_errors = lookup_error('strict')
  1042.     ignore_errors = lookup_error('ignore')
  1043.     replace_errors = lookup_error('replace')
  1044.     xmlcharrefreplace_errors = lookup_error('xmlcharrefreplace')
  1045.     backslashreplace_errors = lookup_error('backslashreplace')
  1046. except LookupError:
  1047.     strict_errors = None
  1048.     ignore_errors = None
  1049.     replace_errors = None
  1050.     xmlcharrefreplace_errors = None
  1051.     backslashreplace_errors = None
  1052.  
  1053. _false = 0
  1054. if _false:
  1055.     import encodings
  1056. if __name__ == '__main__':
  1057.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  1058.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  1059.